package mall.controller;

import java.util.Date;

import mall.pojo.Member;
import mall.service.MemberPositionService;
import mall.service.MemberService;
import mall.service.MemberTypeService;
import mall.util.UtilityClass;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes("userInfo")
public class MemberController {

	@Autowired
	private MemberService memberService;

	@Autowired
	private MemberTypeService memberTypeService;

	@Autowired
	private MemberPositionService memberPositionService;

	// create new member blank object and pass to register.jsp
	@RequestMapping(value = "/register", method = RequestMethod.GET)
	public ModelAndView member() {
		return new ModelAndView(UtilityClass.VIEW_MALL_REGISTER, "member", new Member());
	}

	@RequestMapping(value = "/register", method = RequestMethod.POST)
	public String register(@ModelAttribute("member") Member member,
			BindingResult bindingResult) {
		member.setDate(new Date());
		member.setMemberposition(memberPositionService.getMemberPosition(UtilityClass.MEMBER_POSITION_GUEST)); // set
																			
		member.setMembertype(memberTypeService.getMemberType(UtilityClass.MEMBER_TYPE_LEVEL_1));
																	
		memberService.createMember(member);
		return "redirect:/"+UtilityClass.VIEW_MALL_INDEX;
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login( @RequestParam("username") String userName,
			@RequestParam("password") String passWord) {
		ModelAndView modelAndView= new ModelAndView();
		Member member = memberService.checkLogin(userName, passWord);
		if (member != null) {
			modelAndView.addObject("userInfo", member);
		}
		modelAndView.setViewName(UtilityClass.VIEW_MALL_INDEX);
		return modelAndView;
	}

	@RequestMapping("/sign-out")
	public String signOut(SessionStatus status, WebRequest request) {
		// Member member= (Member)session.getAttribute("userInfo")
		status.setComplete();
		request.removeAttribute("userInfo", WebRequest.SCOPE_SESSION);
		return "redirect:/"+UtilityClass.VIEW_MALL_INDEX;
	}

}
